package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.*;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    //
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleMapper.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    @Override
    public List<User> findAll() {
        List<User> list = userMapper.findAll();
        return list;
    }

    //根据用户名获取能展示给该用户的菜单
    public List<Map<String, Object>> findMenuByUsername(String username) {

        List<Map<String, Object>> data = new ArrayList<>();
        //通过用户名获取用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        //获取用户Id
        Integer userId = user.getId();
        //通过用户Id获取对应的角色
        Set<Role> roles = roleMapper.findByUserId(userId);
        //遍历角色
        for (Role role : roles) {
            //获取角色Id
            Integer roleId = role.getId();
            //通过角色Id获取对应的菜单
            List<Menu> menus = menuMapper.findByRoleId(roleId);
            //遍历菜单，获取等级为一的菜单
            for (Menu menu : menus) {
                //获取菜单级别
                Integer level = menu.getLevel();
                Integer menuId = menu.getId();//获取父级菜单id
                //判断菜单级别是否为1
                if (level == 1) {
                    //创建Map用于存储一级菜单
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("path", menu.getPath());
                    map.put("title", menu.getName());
                    map.put("icon", menu.getIcon());
                    //创建Set<Map>用于存储子菜单集合
                    List<Map<String, Object>> childrenData = new ArrayList<>();
                    //再次遍历所有菜单，获取子菜单
                    for (Menu menu1 : menus) {
                        //获取该菜单的父Id
                        Integer parentMenuId = menu1.getParentMenuId();
                        //判断一级菜单id是否为该子菜单的父id
                        if (menuId == parentMenuId) {
                            //是，创建新的Map用于存储子菜单
                            Map<String, Object> childrenMap = new HashMap<>();
                            //存入所需的数据
                            childrenMap.put("path", menu1.getPath());
                            childrenMap.put("title", menu1.getName());
                            childrenMap.put("linkUrl", menu1.getLinkUrl());
                            childrenMap.put("children", null);
                            childrenData.add(childrenMap);
                        }
                    }
                    map.put("children", childrenData);
                    data.add(map);
                }
            }
        }
        return data;
    }

    //修改密码
    public void edit2password(String password, String telephone) {
        userMapper.editPassword(password,telephone);
    }

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean, String username) {
        //获取查询条件
        String queryString = queryPageBean.getQueryString();
        //获取
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("value", queryString);
        Page<User> page = userMapper.selectByCondition(map);
        long total = page.getTotal();
        List<User> result = page.getResult();
        return new PageResult(total, result);
    }

    //新增用户
    public void add(User user, Integer[] roleIds) {
        //新增用户
        userMapper.add(user);
        //调用自定义方法设置与该用户关联的角色
        setUserAndRole(user.getId(), roleIds);
    }

    //根据用户Id查询用户
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    //根据用户Id查询角色Id
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userMapper.findRoleIdsByUserId(userId);
    }

    //删除用户
    public void delete(Integer id) {
        //先删除关联关系
        userMapper.deleteRole(id);
        //删除用户
        userMapper.delete(id);
    }

    //修改用户
    public void edit(User user, Integer[] roleIds) {
        //删除中间数据
        userMapper.deleteRole(user.getId());
        //修改用户
        userMapper.edit(user);
        //重新建立关联关系
        this.setUserAndRole(user.getId(), roleIds);
    }

    //根据用户id查询关联数据的数量
    public Integer findCountByUserId(Integer userId) {
        return userMapper.findCountByUserId(userId);
    }

    //获取所有的用户排除自己
    public List<User> findUsersExOwn(Integer id) {
        return userMapper.findUsersExOwn(id);
    }

    //设置用户和角色的关联关系
    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        //判断roleIds是否为空
        if (roleIds != null && roleIds.length > 0) {
            //不为空就进行遍历
            for (Integer roleId : roleIds) {
                //创建map容器,存储关联关系
                Map<String, Integer> map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                //向中间表插入数据
                userMapper.setUserAndRole(map);
            }
        }
    }
}
